/**
 * Markdown Mermaid 流程图组件
 * 
 * 使用方式（在 Markdown 中）：
 * ```mermaid
 * graph TD
 *   A[开始] --> B{判断}
 *   B -->|是| C[执行操作]
 *   B -->|否| D[结束]
 * ```
 */

import React, { useEffect, useRef, useState } from 'react';
import mermaid from 'mermaid';
import { Button } from '@/components/ui/button';
import { Copy, Check, ZoomIn, ZoomOut, Maximize2 } from 'lucide-react';

// 初始化 Mermaid 配置
mermaid.initialize({
  startOnLoad: false,
  theme: 'default', // 可选：default, dark, forest, neutral
  themeVariables: {
    primaryColor: '#3b82f6',
    primaryTextColor: '#fff',
    primaryBorderColor: '#2563eb',
    lineColor: '#6b7280',
    secondaryColor: '#10b981',
    tertiaryColor: '#f59e0b',
  },
  flowchart: {
    useMaxWidth: true,
    htmlLabels: true,
    curve: 'basis', // 线条曲线样式
  },
  sequence: {
    useMaxWidth: true,
    mirrorActors: false,
  },
  er: {
    useMaxWidth: true,
  },
  gantt: {
    useMaxWidth: true,
  },
});

/**
 * Mermaid 流程图组件
 * @param {Object} props
 * @param {string} props.content - Mermaid 代码内容
 * @param {string} props.type - 图表类型（用于显示）
 */
export const MarkdownMermaid = ({ content = '', type = 'mermaid' }) => {
  const containerRef = useRef(null);
  const [svg, setSvg] = useState('');
  const [error, setError] = useState(null);
  const [copied, setCopied] = useState(false);
  const [scale, setScale] = useState(1.0);

  // 渲染 Mermaid 图表
  useEffect(() => {
    if (!content || !containerRef.current) return;

    const renderMermaid = async () => {
      try {
        // 生成唯一 ID
        const id = `mermaid-${Math.random().toString(36).substring(2, 9)}`;
        
        // 渲染 SVG
        const { svg: renderedSvg } = await mermaid.render(id, content);
        setSvg(renderedSvg);
        setError(null);
      } catch (err) {
        console.error('Mermaid 渲染失败:', err);
        setError(err.message || '流程图渲染失败');
      }
    };

    renderMermaid();
  }, [content]);

  // 复制源代码
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 缩放控制
  const zoomIn = () => setScale(prev => Math.min(prev + 0.2, 2.0));
  const zoomOut = () => setScale(prev => Math.max(prev - 0.2, 0.5));
  const resetZoom = () => setScale(1.0);

  // 全屏查看
  const openFullscreen = () => {
    const blob = new Blob([svg], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);
    window.open(url, '_blank');
  };

  if (error) {
    return (
      <div className="my-6 border border-red-200 dark:border-red-800 rounded-lg overflow-hidden not-prose">
        <div className="bg-red-50 dark:bg-red-950 px-4 py-3 border-b border-red-200 dark:border-red-800">
          <div className="flex items-center gap-2 text-red-700 dark:text-red-300">
            <span className="text-sm font-medium">❌ Mermaid 渲染错误</span>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-900 p-4">
          <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
          <details className="mt-4">
            <summary className="cursor-pointer text-sm text-gray-600 dark:text-gray-400">
              查看源代码
            </summary>
            <pre className="mt-2 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-x-auto">
              {content}
            </pre>
          </details>
        </div>
      </div>
    );
  }

  return (
    <div className="my-6 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden not-prose">
      {/* 工具栏 */}
      <div className="bg-gray-50 dark:bg-gray-800 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          {/* 左侧：标题和类型 */}
          <div className="flex items-center gap-2">
            <svg className="size-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
            </svg>
            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
              流程图
            </span>
          </div>

          {/* 右侧：操作按钮 */}
          <div className="flex items-center gap-2">
            {/* 缩放控制 */}
            <Button
              variant="outline"
              size="sm"
              onClick={zoomOut}
              disabled={scale <= 0.5}
              title="缩小"
            >
              <ZoomOut className="size-4" />
            </Button>

            <span className="text-sm text-gray-700 dark:text-gray-300 px-2 min-w-[60px] text-center">
              {Math.round(scale * 100)}%
            </span>

            <Button
              variant="outline"
              size="sm"
              onClick={zoomIn}
              disabled={scale >= 2.0}
              title="放大"
            >
              <ZoomIn className="size-4" />
            </Button>

            {/* 重置 */}
            <Button
              variant="outline"
              size="sm"
              onClick={resetZoom}
              disabled={scale === 1.0}
              title="重置缩放"
            >
              1:1
            </Button>

            {/* 复制源代码 */}
            <Button
              variant="outline"
              size="sm"
              onClick={handleCopy}
              title="复制 Mermaid 代码"
            >
              {copied ? (
                <>
                  <Check className="size-4 mr-1 text-green-500" />
                  已复制
                </>
              ) : (
                <>
                  <Copy className="size-4 mr-1" />
                  复制
                </>
              )}
            </Button>

            {/* 全屏查看 */}
            <Button
              variant="outline"
              size="sm"
              onClick={openFullscreen}
              title="新窗口打开"
            >
              <Maximize2 className="size-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Mermaid 图表内容 */}
      <div className="bg-white dark:bg-gray-900 p-6 overflow-auto">
        <div
          ref={containerRef}
          className="flex justify-center items-center transition-transform duration-300"
          style={{ transform: `scale(${scale})`, transformOrigin: 'center top' }}
        >
          {svg ? (
            <div
              className="mermaid-diagram"
              dangerouslySetInnerHTML={{ __html: svg }}
            />
          ) : (
            <div className="p-8 text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-gray-500 dark:text-gray-400">渲染流程图...</p>
            </div>
          )}
        </div>
      </div>

      {/* 底部提示 */}
      <div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-t border-gray-200 dark:border-gray-700">
        <p className="text-xs text-gray-500 dark:text-gray-400 text-center">
          💡 提示：使用工具栏缩放，或点击新窗口查看完整流程图
        </p>
      </div>
    </div>
  );
};

// 设置 displayName 帮助父组件识别
MarkdownMermaid.displayName = 'MarkdownMermaid';

export default MarkdownMermaid;

